<?php

declare(strict_types=1);

namespace app\auto\controller;

use \think\admin\Controller;
use \think\admin\service\SystemService;
use \think\facade\Config;
use \think\facade\Db;

class Table extends Controller
{

    //app目录
    public $appDir;
    //应用列表
    public $childDirs;
    //过滤后的应用列表排除admin,auto应用
    public $apps;


    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'AutoTable';

    public function initialize()
    {

        $this->appDir = $this->app->getBasePath();
        $this->childDirs = scandir($this->appDir);
        $this->dbName = Config::get('database.connections.mysql.database');
        //全局变量或数组在这里定义
    }

    /**
     * 控制器管理
     * @auth true
     * @menu true
     * @login true
     */
    public function index()
    {
        $this->title = '应用管理';
        foreach ($this->childDirs as $childDir) {
            if ($childDir != '.' && $childDir != '..' && $childDir != 'admin' && $childDir != 'curd' && $childDir != 'auto' && $childDir != 'manage' && !strpos($childDir, '.php')) {
                $this->apps[] = $childDir;
            }
        }
        $query = $this->_query($this->table)->where('app', input('app'));
        if (!input('app')) {
            $query->where(['id' => 0]);
        }
        $query->page(false);
    }

    /**
     * 添加应用
     * @auth true
     */
    function add_app()
    {
        if ($this->request->isPost()) {
            if (is_dir($this->appDir . '/' . input('appname'))) {
                $this->error('目录已存在，请手工删除后再创建！');
            } else {
                mkdir($this->appDir . '/' . input('appname'));
                mkdir($this->appDir . '/' . input('appname') . '/controller');
                mkdir($this->appDir . '/' . input('appname') . '/view');
                $this->success('创建空应用成功！请继续添加控制器');
            }
        } else {

            $this->_form($this->table, 'form_app');
        }
    }

    /**
     * 添加控制器
     * @auth true
     */
    function add()
    {
        $this->_form($this->table, 'form');
    }





    /**
     * 编辑
     * @auth true
     */
    function edit()
    {
        $this->_form($this->table, 'form');
    }



    /**
     * 删除
     * @auth true
     */
    public function remove()
    {
        Db::execute("DROP TABLE " . input('app') . "_" . input('name'));
        $this->_delete($this->table);
    }

    /**
     * 生成
     * 
     */
    public function build()
    {
        /****生成表*****/
        //获取表信息
        $table = $this->_query($this->table)->db()->where('id', input('id'))->find()->toArray();
        //删除旧表
        $drop = "DROP TABLE IF EXISTS `" . $table['app'] . "_" . $table['name'] . "`;";
        //获取字段
        $fields = $this->_query('AutoField')->db()->where('table_id', $table['id'])->select()->order('sort desc')->toArray();
        $sql_fields = "";
        foreach ($fields as $field) {
            $sql_fields .= "`" . $field['name'] . "`   " . $field['type'] . " COMMENT '" . $field['title'] . "',\n\t";
        }

        $sql = "create table `" . $table['app'] . "_" . $table['name'] . "`
            (
                `id`    int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
                " . $sql_fields . "
                PRIMARY KEY ( `id` )
            ) ";
        Db::execute($drop);
        Db::execute($sql);


        /*****生成控制器*******/
        //控制器全名
        $conName = root_path() . "app/" . $table['app'] . "/controller/" . ucfirst($table['name']) . ".php";
        $conFile = fopen($conName, "w") or $this->error('创建控制器文件失败，请检查写入权限！');
        $conCode = "<?php
declare (strict_types=1);

namespace app\\" . $table['app'] . "\controller;

use \\think\admin\Controller;

class " . ucfirst($table['name']) . " extends Controller {

    /**
     * 绑定数据表
     * @var string
     */
    private \$table = '" . ucfirst($table['app']) . ucfirst($table['name']) . "';

    public function initialize() {
        \$this->title = '" . $table['title'] . "';
        //全局变量或数组在这里定义
    }

    /**
     * " . $table['title'] . "
     * @auth true
     * @menu true
     * @login true
     */
    public function index() {
        \$this->_query(\$this->table)->page();
    }

    /**
     * 添加
     * @auth true
     */
    function add() {
        \$this->_form(\$this->table, 'form');
    }

    /**
     * 编辑
     * @auth true
     */
    function edit() {
        \$this->_form(\$this->table, 'form');
    }

    /**
     * 删除
     * @auth true
     */
    public function remove() {
        \$this->_delete(\$this->table);
    }

}    
";
        fwrite($conFile, $conCode);
        fclose($conFile);



        /****生成view***/
        //列表
        if (!is_dir(root_path() . "app/" . $table['app'] . "/view/" . $table['name'])) {
            mkdir(root_path() . "app/" . $table['app'] . "/view/" . $table['name']);
        }
        $indexName = root_path() . "app/" . $table['app'] . "/view/" . $table['name'] . "/index.html";
        //字段名称
        $viewTitles = "";
        //字段名
        $viewFields = "";

        foreach ($fields as $k => $v) {
            $viewTitles .= "<th class=\"text-left nowrap\">" . $v['title'] . "</th>\n\t\t";
            $viewFields .= "<td>{\$vo." . $v['name'] . "}</td>\n\t\t";
        }
        $viewFile = fopen($indexName, "w") or $this->error('创建index文件失败，请检查写入权限！');



        $viewCode = "{extend name=\"../../admin/view/main\"}
{block name='button'}
<!--{if auth(\"add\")}-->
<button data-modal='{:url(\"add\")}' class='layui-btn layui-btn-primary layui-btn-sm'>添加</button>
<!--{/if}-->
<!--{if auth(\"remove\")}-->
<button data-action='{:url(\"remove\")}' data-rule=\"id#{key}\" class='layui-btn layui-btn-primary layui-btn-sm'>删除</button>
<!--{/if}-->
{/block}
{block name='content'}
<div class=\"think-box-shadow table-block\">

    <table class=\"layui-table\">
        <thead>
            <tr>
                <th class='list-table-check-td think-checkbox'> <label><input data-auto-none data-check-target='.list-check-box' type='checkbox'></label></th>
                " . $viewTitles . "
                <th class=\"text-center nowrap\" style=\"width: 300px;\">操作</th>
            </tr> 
        </thead>
        <tbody>
            {foreach \$list as \$key=>\$vo}
            <tr>
                <td class=\"list-table-check-td think-checkbox\"><label><input class=\"list-check-box\" type='checkbox' value='{\$vo.id}'></label></td>
                " . $viewFields . "
                <td class=\"text-center\">
                    <!--{if auth(\"edit\")}-->
                    <a class=\"layui-btn layui-btn-sm\" data-dbclick data-modal=\"{:url('edit')}?id={\$vo.id}\">编 辑</a>
                    <!--{/if}-->


                    <!--{if auth(\"remove\")}-->
                    <a class=\"layui-btn layui-btn-sm layui-btn-danger\" data-action=\"{:url('remove')}\" data-confirm=\"确定要删除吗？\" data-value=\"id#{\$vo.id}\">删 除</a>
                    <!--{/if}-->

                </td>
            </tr>
            {/foreach}
        </tbody>
    </table>
    {\$pagehtml|raw|default=''}
</div>

<!-- 自定义脚本区，也可能放 content 中，局部加载限制少-->
<script>

</script>
{/block}";
        fwrite($viewFile, $viewCode);
        fclose($viewFile);

        //form页*********************************
        $formName = root_path() . "app/" . $table['app'] . "/view/" . $table['name'] . "/form.html";
        //字段名称
        $viewTitles = "";
        //字段名
        $formFields = "";
        foreach ($fields as $v) {
            $formFields .= "<div class=\"layui-form-item relative block\">
            <span class=\"color-green font-w7 label-required-prev\">" . $v['title'] . "</span>
            <span class=\"color-desc margin-left-5\">" . $v['note'] . "</span>
            <label class=\"relative block\">
                 <input class=\"layui-input\" name=\"" . $v['name'] . "\" placeholder=\"\" value='{\$vo." . $v['name'] . "|default=''}'>
            </label>
        </div>\n\t\t";
        }
        $viewFile = fopen($formName, "w") or $this->error('创建form文件失败，请检查写入权限！');
        $viewCode = "<form action=\"{:request()->url()}\" autocomplete=\"off\" class=\"layui-form layui-card layui-form-pane\" data-auto=\"true\" method=\"post\">
    <div class=\"layui-card-body padding-40\">
        
        " . $formFields . "

        <div class=\"hr-line-dashed\"></div>
   {notempty name='vo.id'}<input name='id' type='hidden' value='{\$vo.id}'>{/notempty}

        <div class=\"layui-form-item text-center\">
            <button class=\"layui-btn\" type=\"submit\">保存数据</button>
            <button class=\"layui-btn layui-btn-danger\"  data-close type='button'>取消编辑</button>
        </div>
    </div>
</form>
{block name='script'}
<script>
// 脚本部分，默认加载了所有插件
    $(function () {
        // layui 表单组件初始化
        layui.form.render();
        // layui 组件动作初始化
        layui.element.render();  
             
    });
</script>
{/block}";
        fwrite($viewFile, $viewCode);
        fclose($viewFile);
        $this->success('生成完成！');
    }


}
